package com.example.springboot.controller;

import com.example.springboot.exception.MyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyExceptionHandler {



    /**
     * 使用json进行数据返回
     * @param e
     * @return
     */
//    @ResponseBody
//    @ExceptionHandler(MyException.class)
//    public Map<String,Object> handlerException(Exception e){
//        Map<String,Object> map = new HashMap<>();
//        map.put("code","user.not exist");
//        map.put("message",e.getMessage());
//        return map;
//    }

    /**
     * 自适应调整 , json 或者 界面
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MyException.class)
    public String handlerException(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("code","user.not exist");
        map.put("message",e.getMessage());
        request.setAttribute("map",map);
        return "forward:/error";
    }
}
